import { _decorator, Component, Node, Prefab, Pool, instantiate, Button, director, v3, randomRangeInt } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('UITest')
export class UITest extends Component {

    @property(Prefab)
    prefab:Prefab = null;


    private prefabPool: Pool<Node> = null;

    private addBtn: Node = null;

    private reduceBtn: Node = null;

    private activates: Node[] = [];

    start() {

        this.addBtn = this.node.getChildByName("add");
        this.reduceBtn = this.node.getChildByName("reduce");

        this.addBtn.on(Button.EventType.CLICK, this.add, this);
        this.reduceBtn.on(Button.EventType.CLICK, this.reduce, this);
        
        this.prefabPool = new Pool(() => {
            return instantiate(this.prefab!);
        }, 10, (node: Node) => {
            node.removeFromParent();
        });

    }


    add(){
        const node = this.prefabPool.alloc();
        if(!node.parent)
        {
            director.getScene().addChild(node);
        }
        node.active = true;
        const pox = randomRangeInt(0, 2)
        const poz = randomRangeInt(0, 2)
        node.worldPosition = v3(pox,0,poz);
        this.activates.push(node);
    }

    reduce(){
        if(this.activates.length <= 0 ) return;
        let node = this.activates.pop();
        node.active = false;
        this.prefabPool.free(node);
    }
}

